/**
 * Created by zhouli on 18/3/13
 * Email li.zhou@huilianyi.com
 */
//新增成本中心
//编辑成本中心
import React from 'react';
import {Button, Form, Input, Col, Row, Switch, Icon, Select, message} from 'antd';
import CCService from 'containers/setting/cost-center/cost-center.service';
import 'styles/setting/cost-center/new-cost-center.scss';
import {connect} from 'react-redux';
import {deepCopy, messages} from 'share/common';
import {LanguageInput} from 'components/index';
import {costCenterDefault} from "containers/setting/cost-center/cost-center.model";
import Chooser from 'components/chooser';

const Option = Select.Option;
const FormItem = Form.Item;

class NewCostCenter extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      setOfBooks: [],
      costCenterDetail: deepCopy(costCenterDefault)
    }
  }

  componentDidMount() {
    CCService.getTenantAllSob()
      .then(res => {
        this.setState({setOfBooks: res.data})
      })
    if (this.props.params.id === "NEW") {
      //新增
    } else {
      //更新
      this.getCostCenterDetail()
    }
  }

  getCostCenterDetail() {
    CCService.getCostCenterDetail(this.props.params.id)
      .then((response) => {
        this.setState({
          costCenterDetail: response.data,
        })
      });
  }

  //校验名称长度
  validateNameLengthErr = (name) => {
    if (name === null || name === undefined || name === "") {
      message.warn(messages('setting.key336'/*请填写名称*/));
      return true;
    }
    if (name && name.length && name.length > 100) {
      message.warn(messages('setting.key337'/*名称最多输入100个字符*/));
      return true;
    }
  }
  handleSave = (e) => {
    e.preventDefault();
    let costCenterDetail = this.state.costCenterDetail;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        if (values.setOfBooksId === costCenterDetail.setOfBooksName) {
          values.setOfBooksId = costCenterDetail.setOfBooksId;
        }
        //名称涉及到多语言，就不用values
        values.name = costCenterDetail.name;
        if (values.parentCostCenterId.length && values.parentCostCenterId.length > 0) {
          values.parentCostCenterId = values.parentCostCenterId[0].id;
        } else {
          values.parentCostCenterId = null;
        }
        costCenterDetail = Object.assign(costCenterDetail, values);
        if (this.validateNameLengthErr(costCenterDetail.name)) {
          return;
        }
        if (costCenterDetail.id) {
          this.updateCostCenter(costCenterDetail);
        } else {
          this.createCostCenter(costCenterDetail);
        }
      }
    });
  };
  createCostCenter = (costCenter) => {
    this.setState({
      loading: true,
    });
    CCService.createCostCenter(costCenter)
      .then((response) => {
        if (response) {
          this.setState({loading: false});
          this.context.router.goBack();
        }
      })
      .catch(() => {
        this.setState({loading: false});
      })
  }
  updateCostCenter = (costCenter) => {
    this.setState({
      loading: true,
    });
    CCService.updateCostCenter(costCenter)
      .then((response) => {
        if (response) {
          this.setState({loading: false});
          this.context.router.goBack();
        }
      })
      .catch(() => {
        this.setState({loading: false});
      })
  }
  //点击取消，返回
  handleCancel = (e) => {
    e.preventDefault();
    this.context.router.goBack();
  };
  //名称：自定义值列表项多语言
  i18nNameChange = (name, i18nName) => {
    this.state.costCenterDetail.name = name;
    if (this.state.costCenterDetail.i18n) {
      this.state.costCenterDetail.i18n.name = i18nName;
    } else {
      this.state.costCenterDetail.i18n = {
        name: i18nName
      };
    }
  }

  parentCostCenterIdChange = (value) => {

  };
  setOfBooksNameChange = (value) => {
    let costCenterDetail = this.state.costCenterDetail;
    costCenterDetail.setOfBooksId = value;
    this.setState({
      costCenterDetail
    })
  }

  render() {
    const {getFieldDecorator} = this.props.form;
    const {tenantMode} = this.props;
    const {loading, costCenterDetail, setOfBooks} = this.state;
    return (
      <div className="new-cost-center">
        <Form onSubmit={this.handleSave} onChange={this.handleChange}>
          <Row gutter={24}>
            <Col span={8}>
              <FormItem
                label={messages('setting.key367'/*账套*/)}
                colon={true}>
                {getFieldDecorator('setOfBooksId', {
                  initialValue: costCenterDetail.setOfBooksName,
                  rules: [
                    {
                      required: true,
                      message: messages("common.please.enter")
                    },
                  ]
                })(
                  <Select disabled={!tenantMode || costCenterDetail.setOfBooksName}
                          onChange={this.setOfBooksNameChange}
                          placeholder={messages('common.please.select')}>
                    {setOfBooks.map((option) => {
                      return <Option key={option.id}>{option.setOfBooksName}</Option>
                    })}
                  </Select>
                )
                }
              </FormItem>
              <div className="person-group-tips"> {messages('setting.key1523')/*请优先选择账套，之后才能确定父级成本中心*/}
              </div>
            </Col>

            <Col span={8}>
              <FormItem
                label={messages('setting.key364'/*成本中心代码*/)}
                colon={true}>
                {getFieldDecorator('code', {
                  initialValue: costCenterDetail.code,
                  rules: [
                    {
                      required: true,
                      message: messages("common.please.enter")
                    },
                  ]
                })(
                  <Input disabled={(costCenterDetail.id && costCenterDetail.code) || !tenantMode}
                         placeholder={messages("common.please.enter")}/>)
                }
              </FormItem>
              <div className="person-group-tips">
                {
                  messages('setting.key365'/*注：成本中心代码保存后将不可修改*/)
                }
              </div>
            </Col>
            <Col span={8}>
              <FormItem label={messages('setting.key366'/*成本中心名称*/)}>
                {getFieldDecorator('name', {
                  initialValue: costCenterDetail.name,
                  rules: [
                    {
                      required: true,
                      message: `${messages("common.please.enter")},${messages('setting.key343'/*最多输入100个字符*/)}`
                    },
                    {
                      max: 100,
                      message: messages('setting.key343'/*最多输入100个字符*/),
                    }],
                })(
                  <div>
                    <LanguageInput
                      disabled={!tenantMode}
                      key={1}
                      name={costCenterDetail.name}
                      i18nName={costCenterDetail.i18n ? costCenterDetail.i18n.name : ""}
                      isEdit={costCenterDetail.id}
                      nameChange={this.i18nNameChange}
                    />
                  </div>
                )}
              </FormItem>

            </Col>

          </Row>
          <Row gutter={24}>
            <Col span={8}>
              <FormItem
                label={messages('setting.key1518')/*父级成本中心*/}
                colon={true}>
                {getFieldDecorator('parentCostCenterId', {
                  initialValue: costCenterDetail.parentCostCenterId ? [{
                    id: costCenterDetail.parentCostCenterId,
                    name: costCenterDetail.parentCostCenterName
                  }] : [],
                })(
                  //hasItemRecord 需后端传过来，标志是否可以修改
                  <Chooser single={true}
                           disabled={costCenterDetail.hasItemRecord}
                           type="select_cost_center_by_sob"
                           placeholder={messages("common.please.select")}
                           labelKey="name"
                           valueKey="id"
                           onChange={this.parentCostCenterIdChange}
                           listExtraParams={{
                             setOfBooksId: costCenterDetail.setOfBooksId,
                             costCenterId: costCenterDetail.id
                           }}/>
                )
                }
              </FormItem>
            </Col>

            <Col span={8}>
              <FormItem
                label={messages("common.status", {status: ""})}
                colon={true}>
                {getFieldDecorator("enabled", {
                  initialValue: costCenterDetail.enabled,
                  valuePropName: 'checked',
                  rules: [],
                })
                (<Switch checkedChildren={<Icon type="check"/>}
                         unCheckedChildren={<Icon type="cross"/>}/>)
                }
              </FormItem>
            </Col>
          </Row>
          <Button type="primary" loading={loading} htmlType="submit">
            {messages("common.save") /*保存*/}
          </Button>
          <Button onClick={this.handleCancel} style={{marginLeft: 8}}>
            {messages("common.cancel") /*取消*/}
          </Button>
        </Form>
      </div>
    )
  }
}

NewCostCenter.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    profile: state.login.profile,
    user: state.login.user,
    company: state.login.company,
    tenantMode: state.main.tenantMode,
  }
}

const WrappedNewCostCenter = Form.create()(NewCostCenter);
export default connect(mapStateToProps)(WrappedNewCostCenter);
